package me.weijing.common.util;

import java.io.File;
import java.util.List;
import java.util.UUID;

import me.weijing.common.CommonApplication;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.Intent.ShortcutIconResource;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ListAdapter;
import android.widget.ListView;

public class PhoneUtil {
    public static boolean isNetWorkConnection(Context context) {
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeInfo = manager.getActiveNetworkInfo();
        if (activeInfo != null)
            return true;
        else
            return false;
    }

    public static String getLocalMacAddress(Context context) {
        WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();
        String mac = info.getMacAddress();
        if (mac == null) {
            wifi.setWifiEnabled(true);
        }
        mac = info.getMacAddress();
        return mac;
    }

    public static String getUUID() {
        String uuid = UUID.randomUUID().toString();
        // 去掉“-”符号
        return uuid.replaceAll("", "-");
    }

    public static String getUserUUID() {
        boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
        if (sdCardExist) {
            File fileName = new File(me.weijing.common.CommonApplication.getInstance().UUIDCachePath);
            if (fileName.exists()) {
                return FileUtil.readFileContent(fileName);
            }
        }
        return null;
    }

    public static void setUserUUID(String uuid) {
        boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
        if (sdCardExist) {
            FileUtil.writeFile(CommonApplication.getInstance().UUIDCachePath, uuid);
        }
    }

    // 可以通过尺寸判断手机和平板
    public static boolean isPad(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        DisplayMetrics dm = new DisplayMetrics();
        display.getMetrics(dm);
        double x = Math.pow(dm.widthPixels / dm.xdpi, 2);
        double y = Math.pow(dm.heightPixels / dm.ydpi, 2);
        double screenInches = Math.sqrt(x + y);
        if (screenInches >= 6.0) {
            return true;
        }
        return false;
    }

    // 判断手机或者是平板 官方用法
    public static boolean isTablet(Context context) {
        return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }

    /**
     * 获取版本号名称
     * 
     * @param context
     * @return
     */
    public static String getAppVersionName(Context context) {
        String versionName = "";
        try {
            // ---get the package info---
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
            if (versionName == null || versionName.length() <= 0) {
                return "";
            }
        } catch (Exception e) {
            Log.e("VersionInfo", "Exception", e);
        }
        return versionName;
    }

    /**
     * 获取版本号
     * 
     * @param context
     * @return
     */
    public static int getAppVersionCode(Context context) {
        int versionCode;
        PackageManager pm = context.getPackageManager();
        PackageInfo pi = null;
        try {
            pi = pm.getPackageInfo(context.getPackageName(), 0);
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        versionCode = pi.versionCode;
        return versionCode;
    }

    /**
     * 判断输入法是否弹出，如果弹出则
     * 
     * @param content
     */
    public static void hideInputMethod(Activity content) {
        if (content != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) content.getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(content.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    public static void ShowDialog(Context context, String title, String msg, String positiveNote, DialogInterface.OnClickListener positiveListener,
            String negativeNote, DialogInterface.OnClickListener negativeListener, boolean flag) {
        Activity act = (Activity) context;
        if (!act.isFinishing()) {
            new AlertDialog.Builder(context).setTitle(title).setMessage(msg).setPositiveButton(positiveNote, positiveListener)
                    .setNegativeButton(negativeNote, negativeListener).setCancelable(flag).show();
        }
    }

    public static void setUpdateInfo(Context context, int versionCode, String versionPath) {
        SharedPreferences shareSetting = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = shareSetting.edit();
        editor.putInt(CommonApplication.UPDATE_APP_VERSION_CODE, versionCode);
        editor.putString(CommonApplication.UPDATE_APP_VERSION_PATH, versionPath);
        editor.commit();
    }

    public static int getAppUpdateVersionCode(Context context) {
        SharedPreferences shareSetting = PreferenceManager.getDefaultSharedPreferences(context);
        return shareSetting.getInt(CommonApplication.UPDATE_APP_VERSION_CODE, 0);
    }

    public static String getAppUpdateVersionPath(Context context) {
        SharedPreferences shareSetting = PreferenceManager.getDefaultSharedPreferences(context);
        return shareSetting.getString(CommonApplication.UPDATE_APP_VERSION_PATH, "");
    }

    /**
     * 安装软件
     * 
     * @param context
     * @param cacheFilePath
     */
    public static void installApp(Context context, String cacheFilePath) {
        File apkfile = new File(cacheFilePath);
        if (!apkfile.exists()) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

    public static boolean isTopActivity(String packName, Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> tasksInfo = activityManager.getRunningTasks(1);
        if (tasksInfo.size() > 0) {
            // 应用程序位于堆栈的顶层
            if ((packName).equals(tasksInfo.get(0).topActivity.getPackageName())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 创建桌面快捷方式
     */
    public static void createShortcut(Context context, String appName, String activity, int id) {
        SharedPreferences setting = context.getSharedPreferences("silent.preferences", 0);
        boolean firstStart = setting.getBoolean("FIRST_START", true);
        if (firstStart) {
            Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
            shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, appName);
            shortcut.putExtra("duplicate", false);
            ComponentName comp = new ComponentName(context.getPackageName(), activity);
            shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(Intent.ACTION_MAIN).setComponent(comp));
            ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(context, id);
            shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);
            context.sendBroadcast(shortcut);
            Editor editor = setting.edit();
            editor.putBoolean("FIRST_START", false);
            editor.commit();
        }
    }

    /**
     * 设置窗口为全屏
     * 
     * @param activity
     */
    public static void setWindowFeature(Activity activity) {
        activity.requestWindowFeature(Window.FEATURE_NO_TITLE);
        activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    public static void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) { // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0); // 计算子项View 的宽高
            totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }
}
